package com.css.zfzx.fxpg.modules.vulnerability.province.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.zfzx.fxpg.common.platform.Platform;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.fxpg.modules.vulnerability.area.repository.entity.FxVulnerabilityAreaEntity;
import com.css.zfzx.fxpg.modules.vulnerability.area.viewobjects.FxVulnerabilityAreaQueryParams;
import com.css.zfzx.fxpg.modules.vulnerability.area.viewobjects.FxVulnerabilityAreaVO;
import com.css.zfzx.fxpg.modules.vulnerability.province.repository.FxVulnerabilityProvinceNativeRepository;
import com.css.zfzx.fxpg.modules.vulnerability.province.repository.FxVulnerabilityProvinceRepository;
import com.css.zfzx.fxpg.modules.vulnerability.province.repository.entity.FxVulnerabilityProvinceEntity;
import com.css.zfzx.fxpg.modules.vulnerability.province.service.FxVulnerabilityProvinceService;
import com.css.zfzx.fxpg.modules.vulnerability.province.viewobjects.FxVulnerabilityProvinceQueryParams;
import com.css.zfzx.fxpg.modules.vulnerability.province.viewobjects.FxVulnerabilityProvinceVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author leon
 * @date 2020-11-10
 */
@Service
@Slf4j
public class FxVulnerabilityProvinceServiceImpl implements FxVulnerabilityProvinceService {

    @Autowired
    private FxVulnerabilityProvinceRepository fxVulnerabilityProvinceRepository;
    @Autowired
    private FxVulnerabilityProvinceNativeRepository fxVulnerabilityProvinceNativeRepository;

    @Override
    public JSONObject queryFxVulnerabilityProvinces(FxVulnerabilityProvinceQueryParams queryParams, int curPage, int pageSize) {
        Page<FxVulnerabilityProvinceEntity> fxVulnerabilityProvincePage = this.fxVulnerabilityProvinceNativeRepository.queryFxVulnerabilityProvinces(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxVulnerabilityProvincePage);
        return jsonObject;
    }

    @Override
    public List<FxVulnerabilityProvinceEntity> listFxVulnerabilityProvinces(FxVulnerabilityProvinceQueryParams queryParams) {
        return fxVulnerabilityProvinceNativeRepository.listFxVulnerabilityProvinces(queryParams);
    }


    @Override
    public FxVulnerabilityProvinceEntity getFxVulnerabilityProvince(String id) {
        FxVulnerabilityProvinceEntity fxVulnerabilityProvince = this.fxVulnerabilityProvinceRepository.findById(id).orElse(null);
        return fxVulnerabilityProvince;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxVulnerabilityProvinceEntity saveFxVulnerabilityProvince(FxVulnerabilityProvinceEntity fxVulnerabilityProvince) {
        String uuid = UUIDGenerator.getUUID();
        fxVulnerabilityProvince.setId(uuid);
        fxVulnerabilityProvince.setCreateUser(PlatformSessionUtils.getUserId());
        fxVulnerabilityProvince.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.fxVulnerabilityProvinceRepository.save(fxVulnerabilityProvince);
        return fxVulnerabilityProvince;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxVulnerabilityProvinceEntity updateFxVulnerabilityProvince(FxVulnerabilityProvinceEntity fxVulnerabilityProvince) {
        fxVulnerabilityProvince.setUpdateUser(PlatformSessionUtils.getUserId());
        fxVulnerabilityProvince.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxVulnerabilityProvince.getId();
        FxVulnerabilityProvinceEntity one = fxVulnerabilityProvinceRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxVulnerabilityProvince, one);
        this.fxVulnerabilityProvinceRepository.save(one);
        return fxVulnerabilityProvince;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxVulnerabilityProvinces(List<String> ids) {
        List<FxVulnerabilityProvinceEntity> fxVulnerabilityProvinceList = this.fxVulnerabilityProvinceRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(fxVulnerabilityProvinceList) && fxVulnerabilityProvinceList.size() > 0) {
            for (FxVulnerabilityProvinceEntity fxVulnerabilityProvince : fxVulnerabilityProvinceList) {
                this.fxVulnerabilityProvinceRepository.delete(fxVulnerabilityProvince);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置解析从第1+1+1行开始
            params.setTitleRows(1);
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxVulnerabilityProvinceVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxVulnerabilityProvinceVO.class, params);
            List<FxVulnerabilityProvinceVO> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxVulnerabilityProvinceVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxVulnerabilityProvinceVO provinceVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + provinceVO.getRowNum() + "行" + provinceVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if ("库中该数据最多一条，请管理员清理数据库冗余数据！".equals(e.getMessage())) {
                return e.getMessage();
            } else {
                return "导入失败，请检查数据正确性";
            }
        }
    }

    private void saveExcel(List<FxVulnerabilityProvinceVO> list) {
        for (int i = 0; i < list.size(); i++) {
            FxVulnerabilityProvinceEntity provinceEntity = new FxVulnerabilityProvinceEntity();
            FxVulnerabilityProvinceVO provinceVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(provinceVO, provinceEntity);
            saveOrUpdate(provinceEntity);
        }
    }

    /**
     * 保存或者修改（地区-结构类型-破坏程度-烈度,这四个字段值相同的数据只能有一条数据）
     *
     * @param provinceEntity
     */
    @Override
    public void saveOrUpdate(FxVulnerabilityProvinceEntity provinceEntity) {
        FxVulnerabilityProvinceQueryParams queryParams = new FxVulnerabilityProvinceQueryParams();
        queryParams.setProvince(provinceEntity.getProvince());
        queryParams.setCity(provinceEntity.getCity());
        queryParams.setArea(provinceEntity.getArea());
        queryParams.setStructureType(provinceEntity.getStructureType());
        queryParams.setDamageDegree(provinceEntity.getDamageDegree());
        List<FxVulnerabilityProvinceEntity> provinceEntities = fxVulnerabilityProvinceNativeRepository.listFxVulnerabilityProvinces(queryParams);
        // 若查到数据为空，则新增
        if (CollectionUtils.isEmpty(provinceEntities)) {
            this.saveFxVulnerabilityProvince(provinceEntity);
        } else {
            if (provinceEntities.size() == 1) {
                FxVulnerabilityProvinceEntity sourceProvinceEntity = provinceEntities.get(0);
                BeanUtil.copyPropertiesIgnoreNull(provinceEntity, sourceProvinceEntity);
                this.updateFxVulnerabilityProvince(sourceProvinceEntity);
            } else {
                throw new RuntimeException("库中该数据最多一条，请管理员清理数据库冗余数据！");
            }
        }
    }

    @Override
    public String exportExcel(FxVulnerabilityProvinceQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxVulnerabilityProvinceEntity> provinceEntities = fxVulnerabilityProvinceNativeRepository.listFxVulnerabilityProvinces(queryParams);
            // 深拷贝
            ArrayList<FxVulnerabilityProvinceVO> vos = new ArrayList<>();
            for (FxVulnerabilityProvinceEntity provinceEntity : provinceEntities) {
                FxVulnerabilityProvinceVO vo = new FxVulnerabilityProvinceVO();
                BeanUtils.copyProperties(provinceEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "省易损性信息统计", "省易损性信息", FxVulnerabilityProvinceVO.class, "省易损性.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    @Override
    public List<FxVulnerabilityProvinceEntity> findFxVulnerabilityProvince(FxVulnerabilityProvinceQueryParams queryParams) {
        List<FxVulnerabilityProvinceEntity> fxVulnerabilityProvince = this.fxVulnerabilityProvinceNativeRepository.listFxVulnerabilityProvinces(queryParams);
        return fxVulnerabilityProvince;
    }

    @Override
    public void initialize() {
        List<FxVulnerabilityProvinceEntity> all = fxVulnerabilityProvinceRepository.findAll();
        if (all != null && all.size() > 0) {
            throw new RuntimeException("请删除所有数据后进行初始化！");
        } else {
            List<DivisionEntity> provinceDivisions = PlatformAPI.getDivisionAPI().getSubDivisions("root");
            for (DivisionEntity provinceDivision : provinceDivisions) {
                // 省
                String province = provinceDivision.getDivisionName();
                // 直辖市
                if ("北京市".equals(province) || "天津市".equals(province) || "上海市".equals(province) || "重庆市".equals(province)) {
                    // 市
                    String city = province;
                    List<DivisionEntity> areaDivisions = PlatformAPI.getDivisionAPI().getSubDivisions(provinceDivision.getDivisionId());
                    for (DivisionEntity areaDivision : areaDivisions) {
                        // 区
                        String area = areaDivision.getDivisionName();
                        FxVulnerabilityProvinceEntity vulnerabilityProvinceEntity = new FxVulnerabilityProvinceEntity();
                        vulnerabilityProvinceEntity.setProvince(province);
                        vulnerabilityProvinceEntity.setCity(city);
                        vulnerabilityProvinceEntity.setArea(area);
                        // 类型字典值并且保存
                        saveInitialize(vulnerabilityProvinceEntity);
                    }
                }
                // 省下面的正常市
                else {
                    List<DivisionEntity> cityDivisions = PlatformAPI.getDivisionAPI().getSubDivisions(provinceDivision.getDivisionId());
                    for (DivisionEntity cityDivision : cityDivisions) {
                        // 市
                        String city = cityDivision.getDivisionName();
                        List<DivisionEntity> areaDivisions = PlatformAPI.getDivisionAPI().getSubDivisions(cityDivision.getDivisionId());
                        for (DivisionEntity areaDivision : areaDivisions) {
                            // 区
                            String area = areaDivision.getDivisionName();
                            FxVulnerabilityProvinceEntity vulnerabilityProvinceEntity = new FxVulnerabilityProvinceEntity();
                            vulnerabilityProvinceEntity.setProvince(province);
                            vulnerabilityProvinceEntity.setCity(city);
                            vulnerabilityProvinceEntity.setArea(area);

                            // 类型字典值并且保存
                            saveInitialize(vulnerabilityProvinceEntity);
                        }
                    }
                }

            }
        }
    }

    private void saveInitialize(FxVulnerabilityProvinceEntity vulnerabilityProvinceEntity) {
        // 结构类型
        List<DictItemEntity> structureTypes = PlatformAPI.getDictAPI().getValidDictItemsByDictCode("structureType");
        for (DictItemEntity structureType : structureTypes) {
            String structureName = structureType.getDictItemName();
            vulnerabilityProvinceEntity.setStructureType(structureName);
            // 破坏程度
            List<DictItemEntity> damageDegrees = PlatformAPI.getDictAPI().getValidDictItemsByDictCode("damageDegree");
            for (DictItemEntity damageDegree :
                    damageDegrees) {
                String damageDegreeName = damageDegree.getDictItemCode();
                vulnerabilityProvinceEntity.setDamageDegree(damageDegreeName);
                this.saveFxVulnerabilityProvince(vulnerabilityProvinceEntity);
            }
        }
    }

}
